package city.spring.modules.material.controller;

import city.spring.modules.material.entity.MaterialreceiptMaterialExtEntity;
import city.spring.modules.material.repository.MaterialreceiptMaterialExtRepository;
import city.spring.modules.material.service.MaterialreceiptMaterialExtService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Controller：物资领用与物资关系表
 *
 * @author 谢金婷
 * @date 2020-12-17 11:48:32
 */
@RestController
@RequestMapping("/materialreceipt/{materialreceiptId}/material")
public class MaterialreceiptMaterialExtController extends ApiController {
    private final MaterialreceiptMaterialExtService materialreceiptMaterialExtService;
    private final MaterialreceiptMaterialExtRepository materialreceiptMaterialExtRepository;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MaterialreceiptMaterialExtEntity, ?>> entityOrderFields;

    public MaterialreceiptMaterialExtController(MaterialreceiptMaterialExtService materialreceiptMaterialExtService, MaterialreceiptMaterialExtRepository materialreceiptMaterialExtRepository) {
        this.materialreceiptMaterialExtService = materialreceiptMaterialExtService;
        this.materialreceiptMaterialExtRepository = materialreceiptMaterialExtRepository;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MaterialreceiptMaterialExtEntity::getId);
        entityOrderFields.add(MaterialreceiptMaterialExtEntity::getMaterialreceiptId);
        entityOrderFields.add(MaterialreceiptMaterialExtEntity::getMaterialId);
        entityOrderFields.add(MaterialreceiptMaterialExtEntity::getUnitmeasurement);
        entityOrderFields.add(MaterialreceiptMaterialExtEntity::getCode);
        entityOrderFields.add(MaterialreceiptMaterialExtEntity::getReceiptquantity);
        entityOrderFields.add(MaterialreceiptMaterialExtEntity::getRemark);
        entityOrderFields.add(MaterialreceiptMaterialExtEntity::getGmtCreate);
        entityOrderFields.add(MaterialreceiptMaterialExtEntity::getGmtModified);
    }

    @ModelAttribute
    public void getMaterialreceiptId(@PathVariable String materialreceiptId) {
        if (materialreceiptId == null) {
            throw new RuntimeException("领用单ID必须不为空");
        }
        System.out.println("materialreceiptId" + materialreceiptId);
    }

    /**
     * 获取全部的 <strong>物资领用与物资关系表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MaterialreceiptMaterialExtEntity entity) {
        LambdaQueryChainWrapper<MaterialreceiptMaterialExtEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

//    /**
//     * 分页获取 <strong>物资领用与物资关系表</strong> 列表
//     *
//     * @param pageable 分页参数信息
//     */
//    @GetMapping
//    public Object list(@PageableDefault Pageable pageable, MaterialreceiptMaterialExtEntity entity) {
//        LambdaQueryChainWrapper<MaterialreceiptMaterialExtEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MaterialreceiptMaterialExtEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }

    /**
     * 获取领用物资列表
     *
     * @param materialreceiptId
     * @return
     */
    @GetMapping
    public Object list(@PathVariable String materialreceiptId) {
        return success(materialreceiptMaterialExtRepository.getReceiptMaterials(materialreceiptId));
    }

    //    /**
//     * 获取一个 <strong>物资领用与物资关系表</strong>
//     *
//     * @param id 主键ID
//     */
//    @GetMapping("{id}")
//    public Object info(@PathVariable String id) {
//        return success(materialreceiptMaterialExtService.getById(id));
//    }
    @GetMapping("{extId}")
    public Object getInfo(@PathVariable String materialreceiptId, @PathVariable String extId) {
        return success(materialreceiptMaterialExtRepository.getReceiptMaterial(materialreceiptId, extId));
    }

//    /**
//     * 添加一个 <strong>物资领用与物资关系表</strong>
//     *
//     * @param entity 修改后的信息
//     */
//    @PostMapping
//    public Object add(@RequestBody MaterialreceiptMaterialExtEntity entity) {
//        materialreceiptMaterialExtService.saveMaterialreceiptMaterialExt(entity);
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
//    }

    @PostMapping
    public Object addAll(@PathVariable String materialreceiptId, @RequestBody List<MaterialreceiptMaterialExtEntity> materials) {
        // 查出已有的数据
        List<MaterialreceiptMaterialExtEntity> dbMaterials = materialreceiptMaterialExtRepository.getReceiptMaterials(materialreceiptId);

        // 数据库已经存在的物资列表
        Set<String> dbMaterialIdsSet = dbMaterials.stream()
                .map(MaterialreceiptMaterialExtEntity::getMaterialId)
                .collect(Collectors.toSet());
        // 过滤掉已经存在数据库的数据
        List<MaterialreceiptMaterialExtEntity> needSaveMaterials = materials.stream()
                .filter(item -> {
                    item.setMaterialreceiptId(materialreceiptId);
                    String materialId = item.getMaterialId();
                    // 过滤出不存在数据库中的数据
                    return materialId != null && !dbMaterialIdsSet.contains(materialId);
                }).collect(Collectors.toList());

        if (!needSaveMaterials.isEmpty()) {
            materialreceiptMaterialExtService.saveBatch(needSaveMaterials);
        }

        return success(null);
    }


    //    /**
//     * 修改一个 <strong>物资领用与物资关系表</strong>
//     *
//     * @param id     主键ID
//     * @param entity 修改后的信息
//     */
//    @PutMapping("{id}")
//    public Object update(@PathVariable String id, @RequestBody MaterialreceiptMaterialExtEntity entity) {
//        entity.setId(id);
//        materialreceiptMaterialExtService.updateMaterialreceiptMaterialExt(entity);
//        return new ResponseEntity<>(HttpStatus.OK);
//    }
    @PutMapping("{extId}")
    public Object update(@PathVariable String materialreceiptId, @PathVariable String extId, @RequestBody MaterialreceiptMaterialExtEntity extEntity) {
        extEntity.setId(extId);
        extEntity.setMaterialreceiptId(materialreceiptId);
        materialreceiptMaterialExtService.updateMaterialreceiptMaterialExt(extEntity);
        return success(null);
    }

    /**
     * 删除一个 <strong>物资领用与物资关系表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        materialreceiptMaterialExtService.deleteMaterialreceiptMaterialExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>物资领用与物资关系表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        materialreceiptMaterialExtService.deleteMaterialreceiptMaterialExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MaterialreceiptMaterialExtEntity> buildLambdaQuery(MaterialreceiptMaterialExtEntity entity) {
        LambdaQueryChainWrapper<MaterialreceiptMaterialExtEntity> lambdaQuery = materialreceiptMaterialExtService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MaterialreceiptMaterialExtEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMaterialreceiptId()), MaterialreceiptMaterialExtEntity::getMaterialreceiptId, entity.getMaterialreceiptId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMaterialId()), MaterialreceiptMaterialExtEntity::getMaterialId, entity.getMaterialId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUnitmeasurement()), MaterialreceiptMaterialExtEntity::getUnitmeasurement, entity.getUnitmeasurement());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getCode()), MaterialreceiptMaterialExtEntity::getCode, entity.getCode());
        lambdaQuery.eq(entity.getReceiptquantity() != null, MaterialreceiptMaterialExtEntity::getReceiptquantity, entity.getReceiptquantity());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRemark()), MaterialreceiptMaterialExtEntity::getRemark, entity.getRemark());
        lambdaQuery.eq(entity.getGmtCreate() != null, MaterialreceiptMaterialExtEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, MaterialreceiptMaterialExtEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialreceiptMaterialExtEntity> buildQuery(MaterialreceiptMaterialExtEntity entity) {
        QueryWrapper<MaterialreceiptMaterialExtEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getMaterialreceiptId()), "materialreceipt_id", entity.getMaterialreceiptId());
        wrapper.like(StringUtils.isNotBlank(entity.getMaterialId()), "material_id", entity.getMaterialId());
        wrapper.like(StringUtils.isNotBlank(entity.getUnitmeasurement()), "unitmeasurement", entity.getUnitmeasurement());
        wrapper.like(StringUtils.isNotBlank(entity.getCode()), "code", entity.getCode());
        wrapper.eq(entity.getReceiptquantity() != null, "quantity", entity.getReceiptquantity());
        wrapper.like(StringUtils.isNotBlank(entity.getRemark()), "remark", entity.getRemark());
        wrapper.eq(entity.getGmtCreate() != null, "gmt_create", entity.getGmtCreate());
        wrapper.eq(entity.getGmtModified() != null, "gmt_modified", entity.getGmtModified());
        return wrapper;
    }

}
